//
//  HMDiscoverSearchView.swift
//  Weibo12
//
//  Created by HM on 15/12/26.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit
class HMDiscoverSearchView: UIView {

    // 输入框右边的约束
    @IBOutlet weak var textFieldRightConstraint: NSLayoutConstraint!
    // 输入框
    @IBOutlet weak var textField: UITextField!
    // 取消按钮
    @IBOutlet weak var cancelButton: UIButton!
    // 从 xib 里面加载 view
    class func searchView() -> HMDiscoverSearchView {
        return NSBundle.mainBundle().loadNibNamed("HMDiscoverSearchView", owner: nil, options: nil).last! as! HMDiscoverSearchView
    }
    
    
    // awakeFromNib 与 initWithCoder 这两个方法是与 View 从 xib 里面加载才会调用的方法
    
    override func awakeFromNib() {
        
        // xib 完全转成一个 view 
        // xib 里面的子控件连线完成
        
        // 设置左边视图
        let leftView = UIImageView()
        leftView.image = UIImage(named: "searchbar_textfield_search_icon")
        // 指定大小
        leftView.frame.size = CGSizeMake(frame.height, frame.height)
        // contentMode
        // conter 是代表居中，以原样大小显示
        leftView.contentMode = .Center
        textField.leftView = leftView
        textField.leftViewMode = .Always
        
        
        // 
//        textField.layer.borderWidth = 2
//        textField.layer.borderColor = UIColor.purpleColor().CGColor
        // textField.layer.cornerRadius = 5
        
        // textField.cornerRadius = 5
        
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    
    @IBAction func textFieldBeginEditing(sender: AnyObject) {
        print("开始编辑")
        // 执行约束动画
        // 1. 改约束
        // 2. 在动画的代码块里面执行 self.layoutIfNeeded()
        self.textFieldRightConstraint.constant = self.cancelButton.frame.width
        UIView.animateWithDuration(0.25) { () -> Void in
            self.textField.layoutIfNeeded()
        }
    }
    
    @IBAction func cancelButtonClick(sender: UIButton) {
        
        // 1. 退出键盘
        self.textField.resignFirstResponder()
        // 2. 更改
        self.textFieldRightConstraint.constant = 0
        UIView.animateWithDuration(0.25) { () -> Void in
            self.textField.layoutIfNeeded()
        }
    }
    
}
